#!/bin/bash

# 定义 Nginx 的路径和配置文件
NGINX_BIN="/opt/nginx/mynginx/sbin/nginx"
NGINX_CONF="/opt/nginx/mynginx/conf/nginx.conf"

# 使用说明，用来提示输入参数
usage() {
    echo "Usage: sh nginx.sh [start|stop|restart|status]"
    exit 1
}

# 检查 Nginx 是否在运行
is_running() {
    if pgrep -f "$NGINX_BIN -c $NGINX_CONF" > /dev/null; then
        return 0
    else
        return 1
    fi
}

# 启动 Nginx
start() {
    if is_running; then
        echo "Nginx is already running."
    else
        "$NGINX_BIN" -c "$NGINX_CONF"
        if is_running; then
            echo "Nginx started successfully."
        else
            echo "Failed to start Nginx."
        fi
    fi
}

# 停止 Nginx
stop() {
    if is_running; then
        "$NGINX_BIN" -s stop
        if ! is_running; then
            echo "Nginx stopped successfully."
        else
            echo "Failed to stop Nginx."
        fi
    else
        echo "Nginx is not running."
    fi
}

# 重启 Nginx
restart() {
    stop
    sleep 1
    start
}

# 检查 Nginx 状态
status() {
    if is_running; then
        echo "Nginx is running."
    else
        echo "Nginx is not running."
    fi
}

# 根据输入参数，选择执行对应方法，不输入则执行使用说明
case "$1" in
    "start")
        start
        ;;
    "stop")
        stop
        ;;
    "restart")
        restart
        ;;
    "status")
        status
        ;;
    *)
        usage
        ;;
esac